/*
 * @(#)UserAction.java
 * 2011-5-5 下午10:48:18
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import com.google.common.collect.Lists;
import com.qyxx.platform.common.json.JsonOutput;
import com.qyxx.platform.common.module.service.ServiceException;
import com.qyxx.platform.common.module.web.CrudActionSupport;
import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.sysmng.accountmng.entity.Organization;
import com.qyxx.platform.sysmng.accountmng.entity.OrganizationJson;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.accountmng.entity.RoleJson;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.accountmng.entity.UserJson;
import com.qyxx.platform.sysmng.accountmng.entity.UserVo;
import com.qyxx.platform.sysmng.accountmng.service.AccountManager;
import com.qyxx.platform.sysmng.accountmng.service.OrganizationManager;
import com.qyxx.platform.sysmng.dictmng.web.DefinitionCache;
import com.qyxx.platform.sysmng.utils.Constants;
import com.qyxx.platform.sysmng.utils.DictConstants;

/**
 * 用户管理
 * 
 * @author gxj
 * @version 1.0
 * @since 1.6 2011-5-7 下午11:16:37
 */
@Namespace("/sys/account")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({
		@Result(name = CrudActionSupport.RELOAD, location = "user.action", type = "redirect"),
		@Result(name = "userlist", location = "/WEB-INF/content/sys/account/userlist.jsp") ,
		@Result(name = "userinfo", location = "/WEB-INF/content/sys/account/user-info.jsp") 
		})
public class UserAction extends CrudActionSupport<User> {

	private static final long serialVersionUID = 8683878162525847072L;

	private AccountManager accountManager;
	private OrganizationManager organizationManager;
	// -- 页面属性 --//
	private Long id;
	private Long orgId;
	private Long[] ids;
	private List<Long> checkedRoleIds; // 页面中钩选的角色id列表

	private String roleIds;
	private Long userId;
	private Long newValue;
	private String type;
	private String employeeName;//员工姓名
	
	
	public String getType() {
		return type;
	}


	
	public void setType(String type) {
		this.type = type;
	}


	public String getRoleIds() {
		return roleIds;
	}

	
	public void setRoleIds(String roleIds) {
		this.roleIds = roleIds;
	}

	public Long getNewValue() {
		return newValue;
	}

	public void setNewValue(Long newValue) {
		this.newValue = newValue;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}



	// -- ModelDriven 与 Preparable函数 --//
	public void setId(Long id) {
		this.id = id;
	}

	public User getModel() {
		return entity;
	}

	public Long getOrgId() {
		return orgId;
	}

	/**
	 * @param ids
	 */
	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}
	
	
	/**
	 * @return employeeName
	 */
	public String getEmployeeName() {
		return employeeName;
	}



	
	/**
	 * @param employeeName
	 */
	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}



	@Autowired
	public void setOrganizationManager(
			OrganizationManager organizationManager) {
		this.organizationManager = organizationManager;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = accountManager.getUser(id);
		} else {
			entity = new User();
		}
	}

	@JsonOutput
	public String queryList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		//PropertyFilter propertyFilterStatus = new PropertyFilter(
		//		"EQS_status", Constants.IS_USING);
		//filters.add(propertyFilterStatus);
		if (orgId != null) {
			/*String idss = this.accountManager
					.getStringOrgSonId(orgId);
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"INL_organization.id", idss);*/
			String code = this.accountManager.findOrganization(orgId).getOrganizationCode();
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"LIKELS_com.qyxx.platform.sysmng.accountmng.entity.Organization$$$organization.organizationCode", code);
			filters.add(propertyFilterParentOrg);
		}

		pager = accountManager.searchUser(pager, filters);
		Struts2Utils.renderJson(pager);
		return null;
	}

	// -- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		pager = accountManager.searchUser(pager, filters);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		checkedRoleIds = entity.getRoleIds();
		return INPUT;
	}

	@Override
	@JsonOutput
	public String save() throws Exception {
		// 根据页面上的checkbox选择 整合User的Roles Set
		String organizationId = Struts2Utils
				.getParameter("organizationId");
		if (organizationId == null || "".equals(organizationId)) {
			organizationId = "1";
		}
		String managerId = Struts2Utils.getParameter("managerId");
		Organization org = this.organizationManager
				.getOrganizationById(Long.valueOf(organizationId));
		entity.setOrganization(org);
		if (managerId != null && !"".equals(managerId)) {
			User user = this.accountManager.getUser(Long
					.valueOf(managerId));
			entity.setUser(user);
		}
		if (entity.getPassword() == null) {
			User user = accountManager.findUserByLoginName(entity
					.getLoginName());
			if (user != null) {
				throw new ServiceException("用户"
						+ entity.getLoginName() + " 已存在",
						new Exception("用户" + entity.getLoginName()
								+ " 已存在"));
			}
			Md5PasswordEncoder md5 = new Md5PasswordEncoder();
			String pass = DefinitionCache.getValueByKey(DictConstants.SYS_PARAMS_KEY, DictConstants.SYS_PARAMS_KEY_USER_DEFAULT_PASSWORD);
			entity.setPassword(md5.encodePassword(StringUtils.defaultIfBlank(pass, Constants.DEFAULT_PASSWORD)
					, entity.getLoginName()));
		}
		accountManager.saveUser(entity, roleIds);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	public void prepareSaveUserInfo() throws Exception {
		if (id != null) {
			entity = accountManager.getUser(id);
		} else {
			entity = new User();
		}
	}
	
	@JsonOutput
	public String saveUserInfo() throws Exception {
		String organizationId = Struts2Utils
				.getParameter("organizationId");
		if (organizationId == null || "".equals(organizationId)) {
			organizationId = "1";
		}
		String managerId = Struts2Utils.getParameter("managerId");
		Organization org = this.organizationManager
				.getOrganizationById(Long.valueOf(organizationId));
		entity.setOrganization(org);
		if (managerId != null && !"".equals(managerId)) {
			User user = this.accountManager.getUser(Long
					.valueOf(managerId));
			entity.setUser(user);
		}
		if (entity.getPassword() == null) {
			User user = accountManager.findUserByLoginName(entity
					.getLoginName());
			if (user != null) {
				throw new ServiceException("用户"
						+ entity.getLoginName() + " 已存在",
						new Exception("用户" + entity.getLoginName()
								+ " 已存在"));
			}
			Md5PasswordEncoder md5 = new Md5PasswordEncoder();
			String pass = DefinitionCache.getValueByKey(DictConstants.SYS_PARAMS_KEY, DictConstants.SYS_PARAMS_KEY_USER_DEFAULT_PASSWORD);
			entity.setPassword(md5.encodePassword(StringUtils.defaultIfBlank(pass, Constants.DEFAULT_PASSWORD)
					, entity.getLoginName()));
		}
		accountManager.saveUserInfo(entity);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	public void prepareUpdateUserInfo() throws Exception {
			entity = new User();
	}
	@JsonOutput
	public String updateUserInfo() throws Exception{
		//HttpServletRequest request = ServletActionContext.getRequest();
		//HttpSession session = request.getSession();
		User sessionUser = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		sessionUser.setRealName(entity.getRealName());
		sessionUser.setNickname(entity.getNickname());
		sessionUser.setEmail(entity.getEmail());
		sessionUser.setMobilePhone(entity.getMobilePhone());		
		//session.setAttribute(Constants.USER_SESSION_ID, sessionUser);
		accountManager.updateUserInfo(entity);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	@JsonOutput
	public String updatePassWord() throws Exception{
		User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		String oldPass=Struts2Utils.getParameter("oldPass");
		String newPass=Struts2Utils.getParameter("newPass");
		accountManager.updatePassWord(oldPass,newPass,(user!=null?user.getId():userId));
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	@Override
	@JsonOutput
	public String delete() throws Exception {
		accountManager.deleteUser(id);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@JsonOutput
	public String deleteUsers() throws Exception {

		if (ids == null) {
			throw new ServiceException("请选择你要删除的用户", new Exception(
					"请选择你要删除的用户"));
		}
		for (Long id : ids) {
			accountManager.deleteUser(Long.valueOf(id));
		}
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);

		return null;
	}

	@JsonOutput
	public String addInfo() throws Exception {

		if (orgId == null) {
			throw new ServiceException("请选择你要添加用户所属的组织",
					new Exception("请选择你要添加用户所属的组织"));
		}
		Organization org = organizationManager
				.getOrganizationById(orgId);
		OrganizationJson organizationJson = new OrganizationJson();
		organizationJson.setParentId(orgId);
		organizationJson.setParentName(org.getOrganizationName());
		formatMessage.setMsg(organizationJson);
		Struts2Utils.renderJson(formatMessage);

		return null;
	}

	// -- 其他Action函数 --//
	/**
	 * 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkLoginName() {
		HttpServletRequest request = ServletActionContext
				.getRequest();
		String newLoginName = request.getParameter("loginName");
		String oldLoginName = request.getParameter("oldLoginName");

		if (accountManager.isLoginNameUnique(newLoginName,
				oldLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	// -- 页面属性访问函数 --//
	/**
	 * list页面显示用户分页列表.
	 */
	public Page<User> getPager() {
		return pager;
	}

	/**
	 * input页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return accountManager.getAllRole();
	}

	/**
	 * input页面显示用户拥有的角色.
	 */
	public List<Long> getCheckedRoleIds() {
		return checkedRoleIds;
	}

	/**
	 * input页面提交用户拥有的角色.
	 */
	public void setCheckedRoleIds(List<Long> checkedRoleIds) {
		this.checkedRoleIds = checkedRoleIds;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	@Override
	@JsonOutput
	public String view() throws Exception {
		entity = accountManager.getUser(id);
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@JsonOutput
	public String modifyInfo() throws Exception {
		entity = accountManager.getUser(id);
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	public String init() throws Exception {
		return "userlist";
	}
	public String userInfo() throws Exception {
		return "userinfo";
	}
	
	@JsonOutput
	public String queryUserList() throws Exception {
		List<User> list = this.accountManager.getAllUser();
		List<UserJson> listJson = Lists.newArrayList();
		for (User user : list) {
			UserJson userJson = new UserJson();
			userJson.setId(user.getId());
			userJson.setText(user.getRealName());
			listJson.add(userJson);
		}
		formatMessage.setMsg(listJson);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 根据条件查询用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryUserListMobile() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		pager = accountManager.searchUser(pager, filters);
		List<User> list = pager.getResult();
		List<UserVo> listJson = Lists.newArrayList();
		if(list!=null & !list.isEmpty()) {
			for (User user : list) {
				UserVo uv=new UserVo();
				uv.setId(user.getId());
				uv.setLoginName(user.getLoginName());
				uv.setNickName(user.getNickname());
				uv.setOrgName(user.getOrganizationName());
				uv.setRealName(user.getRealName());
				listJson.add(uv);
			}
		}
		formatMessage.setMsg(listJson);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 根据条件分页查询用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryUserPage() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		if (orgId != null) {
			String code = this.accountManager.findOrganization(orgId).getOrganizationCode();
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"LIKELS_com.qyxx.platform.sysmng.accountmng.entity.Organization$$$organization.organizationCode", code);
			filters.add(propertyFilterParentOrg);
		}
		pager = accountManager.searchUser(pager, filters);
		List<User> list = pager.getResult();
		List<UserVo> listJson = Lists.newArrayList();
		if(list!=null & !list.isEmpty()) {
			for (User user : list) {
				UserVo uv=new UserVo();
				uv.setId(user.getId());
				uv.setLoginName(user.getLoginName());
				uv.setNickName(user.getNickname());
				uv.setOrgName(user.getOrganizationName());
				uv.setRealName(user.getRealName());
				listJson.add(uv);
			}
		}
		Page<UserVo> pageVo = new Page<UserVo>();
		pageVo.setPageNo(pager.getPageNo());
		pageVo.setPageSize(pager.getPageSize());
		pageVo.setTotalCount(pager.getTotalCount());
		pageVo.setResult(listJson);
		//formatMessage.setMsg(pageVo);
		Struts2Utils.renderJson(pageVo);
		return null;
	}
	
	/**
	 * 根据条件查询用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String queryUser() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		if (orgId != null) {
			String code = this.accountManager.findOrganization(orgId).getOrganizationCode();
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"LIKELS_com.qyxx.platform.sysmng.accountmng.entity.Organization$$$organization.organizationCode", code);
			filters.add(propertyFilterParentOrg);
		}
		List<User> list = accountManager.findUserList(filters);
		List<UserVo> listJson = Lists.newArrayList();
		if(list!=null & !list.isEmpty()) {
			for (User user : list) {
				UserVo uv=new UserVo();
				uv.setId(user.getId());
				uv.setLoginName(user.getLoginName());
				uv.setNickName(user.getNickname());
				uv.setOrgName(user.getOrganizationName());
				uv.setRealName(user.getRealName());
				listJson.add(uv);
			}
		}
		//formatMessage.setMsg(listJson);
		Struts2Utils.renderJson(listJson);
		return null;
	}

	/**
	 * 查询用户授权角色树
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String treeList() throws Exception {
		List<RoleJson> list = accountManager.getRoleList(newValue);
		formatMessage.setMsg(list);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 查询用户授权角色树，包含已有角色选中
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String selectedList() throws Exception {
		List<RoleJson> list = accountManager.getAllSelectedRole(userId);
		formatMessage.setMsg(list);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
/**
 * 
 * 返回所有用户列表
 * @return
 * @throws Exception
 */
	@JsonOutput
	public String findAllUser() throws Exception{
		Map<Long, UserVo> map=accountManager.getUsers();
		formatMessage.setMsg(map);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	@JsonOutput
	public String resetPassword() throws Exception {
		String pass = DefinitionCache.getValueByKey(DictConstants.SYS_PARAMS_KEY, DictConstants.SYS_PARAMS_KEY_USER_DEFAULT_PASSWORD);
		pass = StringUtils.defaultIfBlank(pass, Constants.DEFAULT_PASSWORD);
		accountManager.resetPass(ids, pass, orgId);
		formatMessage.setMsg("密码重置成功，重置为" + pass);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	/**
	* 根据类型来返回上级或者下级的所有用户
	*/
	@JsonOutput
	public String getUserList() throws Exception{
		User user = (User) Struts2Utils
		.getSessionAttribute(Constants.USER_SESSION_ID);
		List<RoleJson> list = accountManager.getUserByOrganization(user,type);
		formatMessage.setMsg(list);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 变更员工姓名
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String changeEmployeeName() throws Exception {
		accountManager.changeEmployeeName(id, employeeName);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 启用/禁用用户
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String changeStatus() throws Exception {
		accountManager.changeStatus(id, type);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	* 根据条件查询角色列表
	*/
	@JsonOutput
	public String findRoleList() throws Exception{
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		List<Role> roleList = accountManager.findRoleList(filters);
		List<RoleJson> roleJsonList = new ArrayList<RoleJson>();
		if(roleList != null && !roleList.isEmpty()) {
			for(Role role : roleList) {
				RoleJson rj = new RoleJson();
				rj.setId(String.valueOf(role.getId()));
				rj.setName(role.getRoleName());
				roleJsonList.add(rj);
			}
		}
		formatMessage.setMsg(roleJsonList);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
}
